<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>表达式表单</title>
    <link href="//unpkg.com/layui@2.9.14/dist/css/layui.css" rel="stylesheet">
    <script src="//unpkg.com/layui@2.9.14/dist/layui.js"></script>

    <script src="/js/cdn/jquery-3.3.1.min.js"></script>
    <script src="/js/cdn/json-viewer/jquery.json-viewer.js"></script>
    <link href="/js/cdn/json-viewer/jquery.json-viewer.css" type="text/css" rel="stylesheet">

    <script src="/js/Utils.js"></script>
    <script src="/js/engine-const.js"></script>
</head>
<body>
<div id="exp-form-data" style="padding-left: 50px;padding-top: 50px">
    <form action="" class="layui-form layui-form-pane" lay-filter="expression-form">
        <div class="layui-form-item">
            <label class="layui-form-label">表达式类型</label>
            <div class="layui-input-block">
                <select lay-filter="expressType" name="expressionType">
                    <option selected value="action">行为【适合场景: 配置业务类型,明确业务场景】</option>
                    <option value="condition">规则【适合场景: 配置业务规则，匹配业务场景】</option>
                    <option value="trigger">触发【适合场景: 配置业务操作，执行业务场景】</option>
                    <option value="callback">回调【适合场景: 配置回调操作，适合通知类场景】</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">表达式编码</label>
            <div class="layui-col-md8">
                <input autoComplete="off" class="layui-input" lay-verify="required"
                       name="expressionCode"
                       placeholder="请输入编码，该字段用于标识该规则编码，方便后续通过编码查询该表达式是否满足"
                       type="text"/>
            </div>
            <div class="layui-col-md3">
                <button class="layui-btn layui-btn-radius" id="expressionCode-gen" onclick="refreshCode()"
                        type="button">
                    <i class="layui-icon layui-icon-refresh-3"></i>
                </button>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">表达式标题</label>
            <div class="layui-input-block">
                <input autoComplete="off" class="layui-input" lay-verify="required"
                       name="expressionTitle"
                       placeholder="请输入表达式标题，用于中文描述该规则的简称，或者你也可以理解为任务名称"
                       type="text"/>
            </div>
        </div>
        <div class="layui-form-item layui-form-text">
            <label class="layui-form-label" style="height: 52px">表达式内容
                <i class="layui-icon layui-icon-tips" style="padding-top: 10px;padding-left: 10px; color: #16baaa">【Ctrl+ALT+空格,会检索当前光标直至上一个空格位置中间的关键字进行检索】</i>
                <span id="sample_pre_div">
                    <i class="layui-icon layui-icon-fire" style="color: #16baaa">
                        <button class="layui-btn layui-btn-radius" id="expression_translate_body"
                                onclick="getExpressionTranslateBody()" type="button">
                            查看表达式详情
                        </button>
                        <button class="layui-btn layui-btn-radius" id="expression_sample_body"
                                onclick="getExpressionSampleBody()" type="button">
                            查看样本参数
                        </button>
                        <button class="layui-btn layui-btn-radius" id="expression_sample_link"
                                onclick="linkExpressionSampleBody()" type="button">
                            跳转追踪示例
                        </button>
                    </i>
                </span>
            </label>
            <div class="layui-input-block">
                <textarea style="min-height: 150px" class="layui-textarea" id="expression_input_search"
                          name="expressionContent"
                          placeholder="请输入表达式内容,如果为空的情况下建议填true"></textarea>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">表达式描述</label>
            <div class="layui-input-block">
                <input autoComplete="off" class="layui-input" name="expressionDescription" placeholder="请输入"
                       type="text"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">优先级</label>
            <div class="layui-col-md3">
                <input autoComplete="off" class="layui-input" lay-verify="required"
                       name="priorityOrder"
                       placeholder="请输入优先级顺序,数值越高,优先级越高"
                       type="number"/>
            </div>
            <div class="layui-col-md3" style="padding-top: 10px;padding-left: 10px; color: #16baaa">
                <i class="layui-icon layui-icon-tips "></i>数值越高,优先级越高
            </div>
        </div>
        <div class="layui-form-item layui-form-text">
            <label class="layui-form-label">能力开关</label>
            <div class="layui-input-block">
                <input lay-filter="configurability-checkbox-filter" lay-skin="tag" name="enableNodeAsync"
                       title="开启子分支异步"
                       type="checkbox"/>
                <!--                <input lay-filter="configurability-checkbox-filter" lay-skin="tag" name="enableSampleBody" title="样本参数" type="checkbox"/>-->
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">表达式状态</label>
            <div class="layui-input-inline">
                <select lay-filter="expressionStatus" name="expressionStatus">
                    <option selected value="1">有效</option>
                    <option value="0">无效</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <button class="layui-btn" lay-filter="demo1" lay-submit>确认</button>
            <button class="layui-btn layui-btn-primary" type="reset">重置</button>
        </div>
    </form>
</div>
<pre id="json-renderer"></pre>
</body>
<script type="text/javascript">
    var layer = layui.layer;
    var form = layui.form;
    var util = layui.util
    let requestParam = engineUtils.getRequestParams();
    var expressionTypeList = final_const.final_constants.expression_type_list;
    let dataId = requestParam["id"];
    let executorId = requestParam.executorId;
    let api_add_path = final_const.api_path.expression_add;
    let api_edit_path = final_const.api_path.expression_edit;
    let api_expressionFindExpressionInfo = final_const.api_path.expression_findExpressionInfo;
    let api_trace_sample_object = final_const.api_path.trace_sample_object;
    let api_executor_doc_translate_list = final_const.api_path.executor_doc_translate_list;
    let api_executor_doc_search_list = final_const.api_path.executor_doc_search_list;
    // 复选框 - 选择暂存结果
    let configurabilityEnableArray = new Set();
    // 配置开关能力记录,新增的能力需要注册到该配置中
    let configurabilityJson = {};
    let serviceName = null;

    // 代表修改
    if (dataId) {
        let url = api_expressionFindExpressionInfo + "?id=" + dataId;
        engineUtils.requestPost(url, {}, function (response) {
            let defaultData = response.data;
            let configurabilityJson = defaultData['configurabilityJson'];
            if (configurabilityJson) {
                let configJson = JSON.parse(configurabilityJson);
                if (configJson && configJson.enableSwitch) {
                    configJson.enableSwitch.forEach(function (item) {
                        // 初始化配置开关中的复选框
                        defaultData[item] = true;
                        // 暂存事件
                        configurabilityEnableArray.add(item);
                    });
                }
            }
            form.val('expression-form', defaultData);
        })
    } else {
        // 代表新增逻辑
        let nextExpressionTypeIndex = Math.min(expressionTypeList.indexOf(requestParam.expressionType) + 1, 3);
        form.val('expression-form', {
            'expressionType': expressionTypeList[nextExpressionTypeIndex],
            'priorityOrder': 100,
        });
        refreshCode();
        $("#sample_pre_div").remove();
    }

    form.on('checkbox(configurability-checkbox-filter)', function (data) {
        console.log(this.value); // 当前点击的checkbox的value值
        let name = data.elem.name;
        this.checked ? configurabilityEnableArray.add(name) : configurabilityEnableArray.delete(name);
    });

    //引入自定义插件
    layui.config({
        base: '/js/cdn/layui/ext/' //设置自定义插件路径:根据实际路径进行设置
    }).use(['yutons_sug'], function () {
        //创建yutons_sug搜索框提示插件||输入框提示插件实例
        var yutons_sug = layui.yutons_sug;

        //初始化姓名输入提示框
        yutons_sug.render({
            id: "expression_input_search", //设置容器唯一id
            height: "full",
            page: false,
            cols: [
                [{
                    field: 'name',
                    title: '名称'
                }, {
                    field: 'params',
                    title: '参数'
                }, {
                    field: 'describe',
                    title: '描述'
                }, {
                    field: 'example',
                    title: '案例'
                }, {
                    field: 'groupName',
                    title: '分组'
                }, {
                    field: 'type',
                    title: '类型'
                }]
            ], //设置表头
            type: 'sugTable', //设置输入框提示类型：sug-下拉框，sugTable-下拉表格
            url: api_executor_doc_search_list + "?executorId=" + executorId + "&&expressionId=" + (dataId || '') + "&&limit=8&&name=" //设置异步数据接口,url为必填项,params为字段名
            , parseData: function (res) {
                return {
                    "code": res.code === 200 ? 0 : res.code, //解析接口状态
                    // "msg": res.message, //解析提示文本
                    // "count": res.total, //解析数据长度
                    "data": res.data //解析数据列表
                };
            },
            showText: function (res) {
                let text = res.name;
                if (res.type === 'fn') {
                    text = text + "()";
                }
                return text;
            }
        });
    });

    // 刷新编码
    function refreshCode() {
        form.val('expression-form', {
            'expressionCode': generateRandomString(10),
        })
    }

    function getExpressionSampleBody() {
        if (dataId) {
            let jsonConfig = {collapsed: false, withQuotes: true, withLinks: true}
            engineUtils.requestPost(api_trace_sample_object + "?expressionId=" + dataId, {}, function (response) {
                if (response.code === 200) {
                    let data = response.data || {'envBody': '{}'};
                    showJsonView(data.envBody);
                } else {
                    layer.msg(response.message);
                }
            })
        }
    }

    function showJsonView(data) {
        let jsonConfig = {collapsed: false, withQuotes: true, withLinks: true}
        let jsonBody = data;
        if (typeof data === 'string') {
            jsonBody = JSON.parse(data);
        }
        $('#json-renderer').jsonViewer(jsonBody, jsonConfig);
        layer.open({
            title: '查看表达式详情',
            type: 1,
            offset: 'r',
            anim: 'slideLeft', // 从右往左
            area: ['320px', '100%'],
            shade: 0.1,
            shadeClose: true,
            content: $('#json-renderer').show()
        });
    }

    /**
     * 获取表达式翻译详情
     */
    function getExpressionTranslateBody() {
        if (dataId) {
            engineUtils.requestPost(api_executor_doc_translate_list + "?expressionId=" + dataId, {}, function (response) {
                if (response.code === 200) {
                    let data = response.data || [];
                    showJsonView(data);
                } else {
                    layer.msg(response.message);
                }
            })
        }
    }

    function linkExpressionSampleBody() {
        engineUtils.requestPost(api_trace_sample_object + "?expressionId=" + dataId, {}, function (response) {
            if (response.code === 200) {
                if (!response.data) {
                    layer.msg('没有找到对应的追踪信息!');
                    return;
                }
                let data = response.data;
                util.openWin({
                    url: `/template/expression-rule-config.html?traceLogId=${data.id}&executorId=${data.executorId}&executorCode=${data.executorCode}&executorDescription=${encodeURIComponent(data.executorName)}`
                });
            } else {
                layer.msg(response.message);
            }
        })
    }

    // 提交事件
    form.on('submit(demo1)', function (data) {
        let field = data.field; // 获取表单字段值

        field['executorId'] = requestParam.executorId;
        field['parentId'] = requestParam.parentId;
        configurabilityJson['enableSwitch'] = Array.from(configurabilityEnableArray);
        field['configurabilityJson'] = JSON.stringify(configurabilityJson);

        let submitUrl = api_add_path;
        if (dataId) {
            field['id'] = dataId;
            submitUrl = api_edit_path;
        }

        engineUtils.requestPost(submitUrl, field, function (response) {
            // 请求成功时的回调函数
            console.log(response);

            if (response.code === 200) {
                field["id"] = response.data.id;
                layer.alert('操作成功!', {
                    icon: 6,
                    title: '提示'
                }, function (index, layero, that) {
                    parent.reloadMind();
                    parent.layer.closeAll(); // 关闭弹层
                });
            } else {
                layer.alert(response.message, {
                    title: '错误提示'
                });
                parent.reloadMind();
            }
        })

        // 此处可执行 Ajax 等操作
        // …
        return false; // 阻止默认 form 跳转
    });

    // 生成指定长度的随机字符串
    function generateRandomString(length) {
        const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        let result = '';
        for (let i = 0; i < length; i++) {
            result += characters.charAt(Math.floor(Math.random() * characters.length));
        }
        return result;
    }
</script>
</html>
